package com.daoshu.mds.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daoshu.component.exception.BusinessException;
import com.daoshu.mds.dispatch.entity.MicroGroupEntity;
import com.daoshu.mds.dispatch.entity.MicroGroupMemberEntity;
import com.daoshu.mds.dispatch.entity.MicroGroupMessageEntity;
import com.daoshu.mds.dispatch.qo.MicroMessageQO;
import com.daoshu.mds.message.mapper.MicroGroupMessageMapper;
import com.daoshu.mds.message.service.IMicroGroupMemberService;
import com.daoshu.mds.message.service.IMicroGroupMessageService;
import com.daoshu.mds.message.service.IMicroGroupService;
import com.daoshu.system.bo.AccountBo;
import com.daoshu.system.entity.PersonEntity;
import com.daoshu.system.service.PersonFeignService;
import com.daoshu.system.utils.RequestUtils;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  微群消息服务实现类
 * </p>
 *
 * @author zhaoyanjiang
 * @since 2018-09-10
 */
@Service
public class MicroGroupMessageServiceImpl extends ServiceImpl<MicroGroupMessageMapper, MicroGroupMessageEntity> implements IMicroGroupMessageService {

	@Autowired private RequestUtils userUtil;
	@Autowired @Lazy private IMicroGroupMemberService microGroupMemberService;
	@Autowired private IMicroGroupService microGroupService;
	@Autowired private PersonFeignService personService;
	
	@Override
	public IPage<MicroGroupMessageEntity> queryMicroMessage(MicroMessageQO qo) {
		AccountBo user = userUtil.getCurrentUser();
		MicroGroupMessageEntity entity = new MicroGroupMessageEntity();
		BeanUtils.copyProperties(qo, entity);
		QueryWrapper<MicroGroupMessageEntity> queryWrapper = new QueryWrapper<>(entity);
		queryWrapper.orderByDesc("create_time_");
		IPage<MicroGroupMessageEntity> page = this.page(new Page<>(qo.getStart(), qo.getSize()), queryWrapper);
		List<MicroGroupMessageEntity> list = Optional.ofNullable(page.getRecords()).orElse(new ArrayList<>());
		if (Collections.isEmpty(list)) {
			return page;
		}
		list.sort(new Comparator<MicroGroupMessageEntity>() {

			@Override
			public int compare(MicroGroupMessageEntity o1, MicroGroupMessageEntity o2) {
				if(o1 == null || o2 == null)
					return 0;
				return o1.getCreateTime().after(o2.getCreateTime())?1:-1;
			}
		});
		List<String> personIds = new ArrayList<>();
		list.forEach(message->personIds.add(message.getCreateId()));
		Collection<PersonEntity> persons = Optional.ofNullable(personService.listByIds(personIds)).orElse(new ArrayList<>());
		list.forEach(message->{
			message.setIsOther(!user.getPersonBo().getId().equals(message.getCreateId())?true:false);
			persons.forEach(person->{
				if(message.getCreateId()!=null&&message.getCreateId().equals(person.getId())) {
					message.setHeadUrl(person.getAvator());
					message.setCreateName(person.getName());
				}
			});
		});
		return page;
	}

	@Override
	public Integer getUnreadMessage(String groupId, String personId) {
		if(groupId!=null) {
			MicroGroupMemberEntity memberEntity = microGroupMemberService.getOne(new QueryWrapper<MicroGroupMemberEntity>().eq("person_id_", personId).eq("micro_group_id_", groupId));
			QueryWrapper<MicroGroupMessageEntity> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("micro_group_id_", groupId).gt("create_time_", memberEntity.getReadedTime());
			return this.count(queryWrapper);
		}else {
			return microGroupService.getUnreadCount(personId);
		}
	}

	@Override
	public boolean sendMicroGroupMessage(MicroGroupMessageEntity message) {
		if(message == null) {
			throw new BusinessException(500, "发送消息不能为空");
		}
		AccountBo user = userUtil.getCurrentUser();
		Optional.ofNullable(microGroupMemberService.getOne(new QueryWrapper<MicroGroupMemberEntity>().lambda()
				.eq(MicroGroupMemberEntity::getPersonId, user.getPersonId())
				.eq(MicroGroupMemberEntity::getMicroGroupId, message.getMicroGroupId()))).orElseThrow(()->{
					return new BusinessException(500, "您不是此微群成员，请联系群主");
				});
		message.setCreateId(user.getPersonBo().getId());
		message.setCreateName(user.getPersonBo().getName());
		message.setCreateTime(new Date());
		return this.save(message);
	}

	@Override
	public IPage<MicroGroupMessageEntity> queryConfienceMessage(MicroMessageQO qo) {
		MicroGroupEntity group = Optional.ofNullable(microGroupService.getOne(new QueryWrapper<MicroGroupEntity>().eq("conference_id_", qo.getConferenceId()))).orElseThrow(()->{
			return new BusinessException(500, "此会议室没有聊天记录");
		});
		qo.setMicroGroupId(group.getId());
		return this.queryMicroMessage(qo);
	}

	@Override
	public IPage<MicroGroupMessageEntity> queryImportMessage(MicroMessageQO qo) {
		AccountBo user = userUtil.getCurrentUser();
		Date importRadTime = getImportReadTime(qo.getMicroGroupId(),user.getPersonId());
		MicroGroupMessageEntity entity = new MicroGroupMessageEntity();
		entity.setImportMessageFlag(1);
		BeanUtils.copyProperties(qo, entity);
		QueryWrapper<MicroGroupMessageEntity> queryWrapper = new QueryWrapper<>(entity);
		if(null != importRadTime)
			queryWrapper.gt("create_time_", importRadTime);
		queryWrapper.orderByDesc("create_time_");
		IPage<MicroGroupMessageEntity> page = this.page(new Page<MicroGroupMessageEntity>(qo.getStart(), qo.getSize()),queryWrapper);
		return page;
	}
	private Date getImportReadTime(String groupId,String personId) {
		MicroGroupMemberEntity member = microGroupMemberService.getOne(new QueryWrapper<MicroGroupMemberEntity>().lambda()
				.eq(MicroGroupMemberEntity::getMicroGroupId, groupId)
				.eq(MicroGroupMemberEntity::getPersonId, personId));
		return Optional.ofNullable(member).orElse(new MicroGroupMemberEntity()).getReadImportTime();
	}

	@Override
	public void setupImportMessage(String messageId) {
		MicroGroupMessageEntity message = this.getById(messageId);
		if(null == message)
			throw new BusinessException(500, "不存在的消息,无法设置为重要消息");
		message.setImportMessageFlag(1);
		this.updateById(message);
	}

	/**
	 * 查询微群重要消息记录历史记录
	 *
	 * @param qo
	 * @return
	 */
	@Override
	public IPage<MicroGroupMessageEntity> queryImportHistoryMicroMessage(MicroMessageQO qo) {
		MicroGroupMessageEntity entity = new MicroGroupMessageEntity();
		entity.setImportMessageFlag(1);
		BeanUtils.copyProperties(qo, entity);
		QueryWrapper<MicroGroupMessageEntity> queryWrapper = new QueryWrapper<>(entity);
		queryWrapper.orderByDesc("create_time_");
		IPage<MicroGroupMessageEntity> page = this.page(new Page<MicroGroupMessageEntity>(qo.getStart(), qo.getSize()), queryWrapper);
		return page;
	}

	/**
	 * 取消重要消息设置
	 *
	 * @param messageId 重要消息id
	 * @return
	 */
	@Override
	public boolean cancalSettingImportant(String messageId) {
		MicroGroupMessageEntity message = this.getById(messageId);
		if (null == message) {
			throw new BusinessException(500, "不存在的消息,取消重要消息设置");
		}
		message.setImportMessageFlag(0);
		return this.updateById(message);
	}
}
